/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package libraries;

import java.io.File;
import java.util.ArrayList;

/**
 *
 * @author aeguzkiza
 */
public class FileLibrary {
    public static class MyException extends Exception {
        static final int FileError = 1;
        static final int FileNotDeleted = 2;
        static final int FileNotMoved = 3;
        private int type;
        private String string;

        public MyException(int type, String string) {
            super();
            this.type = type;
            this.string = string;
        }

        @Override
        public String getMessage() {
            switch (type) {
            case FileError:
                    return "ARCHIVO NO ENCONTRADO.\nNo se ha encontrado el archivo correspondiente a la adquisición seleccionada en la ruta:\n["+string+" ]";
            case FileNotDeleted:
                    return "ERROR AL ELIMINAR UN FICHERO.\n"+string+"\n\nAsegúrese de que el archivo existe y de tener permisos de administrador en el equipo.";
            case FileNotMoved:
                    return "ERROR AL MOVER UN FICHERO.\n"+string+"\n\nAsegúrese de que el archivo existe y de tener permisos de administrador en el equipo.";
            default:
                    return "ERROR DESCONOCIDO: string = "+string+" type = "+type;
            }
        }
    }
        
    PathLibrary PL = new PathLibrary();
    
    // Global variables    
    private boolean isError = false;
    private String error = "";
    

    public boolean moveFile(String fileName, String inPath,String outPath) throws MyException {
        // Moves a file to a new directory.
        System.out.println("fileName: "+fileName+" inPath: "+inPath+" outPath: "+outPath+"\\"+fileName);
        File inFile = new File(inPath);     // Creates or reads the input file.
        boolean moved = false;

        File outDir = new File(outPath);    
        if(!outDir.exists()){outDir.mkdir();}   // Creates the output directory if it doesn't exist.
        // Checks if file or directory exists and isn't write protected
        if (!inFile.exists())throw new MyException(MyException.FileNotMoved, "El siguiente archivo o directorio no existe:\n[" +inPath+"]");
        if (!inFile.canWrite())throw new MyException(MyException.FileNotMoved,"El siguiente archivo no tiene permisos de escritura:\n[" +inPath+"]");
        // If it is a directory don't delete it
        if (inFile.isDirectory()) {throw new MyException(MyException.FileNotMoved,"La siguiente ruta corresponde a un directorio, no a un archivo:\n["+inPath+"]");}
        
        moved = inFile.renameTo(new File(outDir, fileName));    // Move the file.
        if (!moved) {throw new MyException(MyException.FileNotMoved, "El siguiente archivo no se ha podido mover a la carpeta de la base de datos:\n["+fileName+"]");}

        return moved;
    }
    public boolean deleteFile(String inFile) throws MyException{
        // Deletes a file.
        File f = new File(inFile);
        // Checks if file or directory exists and isn't write protected
        if (!f.exists())throw new MyException(MyException.FileNotDeleted, "El siguiente archivo o directorio no existe:\n[" +inFile+"]");
        if (!f.canWrite())throw new MyException(MyException.FileNotDeleted,"El siguiente archivo no tiene permisos de escritura:\n[" +inFile+"]");
        // If it is a directory don't delete it
        if (f.isDirectory()) {throw new MyException(MyException.FileNotDeleted,"La siguiente ruta corresponde a un directorio, no a un archivo:\n[" +inFile+"]");}
        // Delete the file
        boolean deleted = f.delete();
        //System.out.println("deleted: "+deleted);
        if (!deleted){throw new MyException(MyException.FileNotDeleted, "El siguiente archivo no se ha podido mover a la carpeta de la base de datos:\n[" +f.getName()+"]");}
        return deleted;
    }

    public String[] getFileList(String inPath){
        // Obtains a list of files/folders in a path.
        File f = new File(inPath);
        String[] files = f.list();
        return files;
    }

    public ArrayList getFilesOnFolder(String inPath, String filetype){
        // Obtains a list of acquisition-files in the folder.
        ArrayList FolderpathList = new ArrayList();
        String[] fileList = getFileList(inPath);
        String extension;
        int i = 0;
        for (int j=0;j<=fileList.length-1;j++){

            int dotPos = fileList[j].lastIndexOf(".");  // Directories doesn't have dot in their path!
            //System.out.println("dotPos: "+dotPos);
            if(dotPos >= 0){
                extension = fileList[j].substring(dotPos);
                System.out.println("Current extension: "+extension+" >> MATCHER RESULT: "+extension.matches(filetype));
                if(extension.matches(filetype) == true){    // The file extension must coincide to get only the files we want.
                    FolderpathList.add(inPath+"\\"+fileList[j]);
                    System.out.println("Accepted file number "+i+" is the "+j+"th in the folder. Has path: "+FolderpathList.get(i)+"\n");
                    i++;
                }
            }
        }
        System.out.println("Number of files in folder: "+FolderpathList.size());
        return FolderpathList;
    }

    public String isInFolder(String inPath, String fileName, ArrayList FolderpathList) throws MyException{
        // Compares the name a file, with available files on the search folder.
        String currentFilePath = inPath+"\\"+fileName;       // Adds the path to the current file name.
        int j = 0;
        while(!FolderpathList.get(j).equals(currentFilePath+".dcm") && !FolderpathList.get(j).equals(currentFilePath+".DCM")){  // The .dcm extension it's com,pared at the end.
            System.out.println("Currently comparing file in folder: "+FolderpathList.get(j)+" >>> File name to Match: "+currentFilePath+"[.dcm OR .DCM]");
            if(j >= FolderpathList.size()-1){
                System.out.println("FILE NOT FOUND ON THE FOLDER");
                //JOptionPane.showMessageDialog(GUI.JFrameBase.Send, "ERROR: Datos de entrada incorrectos");
                this.isError = true;
                this.error = "Archivo no encontrado en el disco duro";
                System.err.println("File not found: there is not file to be sent: [" + currentFilePath+".dcm]");
                throw new MyException(MyException.FileError, currentFilePath+".dcm");
            }
            j++;
        }
        String File2Send = (String) FolderpathList.get(j);
        System.out.println("<<< Matched file path: "+File2Send+" >>>");
        return File2Send;
    }
}

